package com.naughty.shopapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.naughty.shopapi.mapper.CollectsMapper;
import com.naughty.shopapi.mapper.GoodsMapper;
import com.naughty.shopapi.mapper.UsersMapper;
import com.naughty.shopapi.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.naughty.shopapi.utils.JWTUtil.isExpiration;

@Api(tags = "收藏商品操作")
@RestController
@RequestMapping("api")
public class CollectsController {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private CollectsMapper collectsMapper;

    /**
     * 我的收藏数据
     *
     * @param page
     * @return
     */
    @ApiOperation("获取用户收藏商品")
    @GetMapping("/collects")
    public ResponseEntity<Object> getCollects(@RequestParam(defaultValue = "1") Integer page) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        final String Authorization = request.getHeader("authorization");
        String[] tokens = Authorization.split(" ");
        String token = tokens[1];
        final HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("remember_token", token);
        final List<Users> isToken = usersMapper.selectByMap(tokenMap);
        if (isToken.size() == 0) {
            final RegisterErrors registerErrors = new RegisterErrors();
            registerErrors.setMessage("The token has been blacklisted.");
            registerErrors.setErrors("Token已被列入黑名单");
            registerErrors.setStatus_code(401);
            return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
        } else {
            if (!isExpiration(token)) {//判断token有效期
                int pageAbs = 1;    //正负过滤
                if (page <= 1) {
                    pageAbs = 1;
                } else {
                    pageAbs = Math.abs(page);
                }
                final MetaListVO metaListVO = new MetaListVO();//data and meta
                final List<CollectsVO> CollectsVOOUT = new ArrayList<>();//放置所有收藏项
                final MetaPaginationVO metaPaginationVO = new MetaPaginationVO();
                final Meta meta = new Meta();


                final QueryWrapper<Collects> wrapperCollectsUid = new QueryWrapper<>();//查询该用户的所有收藏商品
                wrapperCollectsUid.eq("user_id", isToken.get(0).getId());
                final Page<Collects> CollectsPage = new Page<>(pageAbs, 10);
                collectsMapper.selectPage(CollectsPage, wrapperCollectsUid);//CollectsPage.getRecords()获取所有条件列

                for (int i = 0; i < CollectsPage.getRecords().size(); i++) {
                    final CollectsVO collectsVO = new CollectsVO(); //data -> object
                    final Goods goods = new Goods();
                    final QueryWrapper<Goods> wrapperGoodUid = new QueryWrapper<>();//查询对应用户收藏商品的信息
                    wrapperGoodUid.eq("id", CollectsPage.getRecords().get(i).getGoods_id());
                    List<Goods> GoodListByUid = goodsMapper.selectList(wrapperGoodUid);
                    collectsVO.setId(CollectsPage.getRecords().get(i).getId());
                    collectsVO.setUser_id(CollectsPage.getRecords().get(i).getUser_id());
                    collectsVO.setGoods_id(CollectsPage.getRecords().get(i).getGoods_id());
                    //对应收藏商品信息赋值
                    goods.setId(GoodListByUid.get(0).getId());
                    goods.setUser_id(GoodListByUid.get(0).getUser_id());
                    goods.setCategory_id(GoodListByUid.get(0).getCategory_id());
                    goods.setTitle(GoodListByUid.get(0).getTitle());
                    goods.setDescription(GoodListByUid.get(0).getDescription());
                    goods.setPrice(GoodListByUid.get(0).getPrice());
                    goods.setStock(GoodListByUid.get(0).getStock());
                    goods.setSales(GoodListByUid.get(0).getSales());
                    goods.setCover(GoodListByUid.get(0).getCover());
                    goods.setPics(GoodListByUid.get(0).getPics());
                    goods.setIs_on(GoodListByUid.get(0).getIs_on());
                    goods.setIs_recommend(GoodListByUid.get(0).getIs_recommend());
                    goods.setDetails(GoodListByUid.get(0).getDetails());
                    goods.setCreated_at(GoodListByUid.get(0).getCreated_at());
                    goods.setUpdated_at(GoodListByUid.get(0).getUpdated_at());
                    goods.setCollects_count(GoodListByUid.get(0).getCollects_count());
                    goods.setCover_url(GoodListByUid.get(0).getCover_url());
                    goods.setPics_url(GoodListByUid.get(0).getPics_url());
                    goods.setIs_collect(GoodListByUid.get(0).getIs_collect());

                    collectsVO.setGoods(goods);
                    collectsVO.setCreated_at(CollectsPage.getRecords().get(i).getCreated_at());
                    collectsVO.setUpdated_at(CollectsPage.getRecords().get(i).getUpdated_at());
                    CollectsVOOUT.add(collectsVO);
                }

                final float pageCount = (float) CollectsPage.getTotal() / 10;
                final double currentPageCount = Math.ceil(pageCount);
                meta.setTotal(CollectsPage.getTotal()); //数据总数
                meta.setCount(CollectsPage.getRecords().size());//当前页数据条数
                meta.setPer_page(10);//每页数据条数
                meta.setCurrent_page(pageAbs);//当前页码
                meta.setTotal_pages((int) currentPageCount);//总页数CollectsPage.getTotal()|((long) floor < 1) ? 1 : (long) floor
                if (currentPageCount <= 1) {
                    meta.setLinks(null);
                } else {
                    String path = "http://localhost:8182/api/collects";
                    if (pageAbs <= currentPageCount) {
                        if (pageAbs == 1) {
                            final HashMap<String, Object> linkMap = new HashMap<>();
                            linkMap.put("previous", null);
                            linkMap.put("next", path + "?page=" + (pageAbs + 1));
                            meta.setLinks(linkMap);
                        } else {
                            if (pageAbs == currentPageCount) {
                                final HashMap<String, Object> linkMap = new HashMap<>();
                                linkMap.put("previous", path + "?page=" + (pageAbs - 1));
                                linkMap.put("next", null);
                                meta.setLinks(linkMap);
                            } else {
                                final HashMap<String, Object> linkMap = new HashMap<>();
                                linkMap.put("previous", path + "?page=" + (pageAbs - 1));
                                linkMap.put("next", path + "?page=" + (pageAbs + 1));
                                meta.setLinks(linkMap);
                            }
                        }
                    } else {
                        meta.setLinks(null);
                    }
                }
                metaPaginationVO.setPagination(meta);
                metaListVO.setData(CollectsVOOUT);
                metaListVO.setMeta(metaPaginationVO);
                return new ResponseEntity<>(metaListVO, HttpStatus.OK);
            } else {
                final RegisterErrors registerErrors = new RegisterErrors();
                registerErrors.setMessage("Token Signature could not be verified.");
                registerErrors.setErrors("Token已失效");
                registerErrors.setStatus_code(401);
                return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
            }
        }
    }

    /**
     * 收藏和取消收藏
     *
     * @param good
     * @return
     */

    @ApiOperation("用户收藏商品和取消商品")
    @PostMapping("/collects/goods/{good}")
    public ResponseEntity<Object> setCollects(@PathVariable("good") Integer good) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        final String Authorization = request.getHeader("authorization");
        String[] tokens = Authorization.split(" ");
        String token = tokens[1];
        final HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("remember_token", token);
        final List<Users> isToken = usersMapper.selectByMap(tokenMap);
        if (isToken.size() == 0) {
            final RegisterErrors registerErrors = new RegisterErrors();
            registerErrors.setMessage("The token has been blacklisted.");
            registerErrors.setErrors("Token已被列入黑名单");
            registerErrors.setStatus_code(401);
            return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
        } else {
            if (!isExpiration(token)) {//判断token有效期
                final QueryWrapper<Goods> wrapperIsGoods = new QueryWrapper<>();//查询该用户的所有收藏商品
                wrapperIsGoods.eq("id", good);
                final List<Goods> isGoods = goodsMapper.selectList(wrapperIsGoods);
                if (isGoods.size() != 0) {//先判断是否存在该商品
                    final QueryWrapper<Collects> wrapperIsCollect = new QueryWrapper<>();//查询该用户的所有收藏商品
                    wrapperIsCollect.eq("user_id", isToken.get(0).getId());
                    wrapperIsCollect.eq("goods_id", good);
                    final List<Collects> collects = collectsMapper.selectList(wrapperIsCollect);
                    if (collects.size() == 0) {//此用户从未收藏过此商品--收藏
                        //找不到数据，新建一条收藏数据---收藏
                        /*final QueryWrapper<Collects> wrapperCollectCount = new QueryWrapper<>();//查询收藏列表中该商品的所有收藏
                        wrapperCollectCount.eq("goods_id", good);
                        final List<Collects> collectsListAll = collectsMapper.selectList(wrapperCollectCount);
                        if (collectsListAll.size() == 0) {//如果没有，则代表从未被收藏，令is_collect=1

                        }*/
                        UpdateWrapper<Goods> updateWrapperIsCollect = new UpdateWrapper<>();
                        updateWrapperIsCollect.eq("id", good).set("is_collect", 1);
                        goodsMapper.update(null, updateWrapperIsCollect);
                        //collects表中插入该商品数据
                        final Collects collectsObj = new Collects();
                        collectsObj.setGoods_id(good);
                        collectsObj.setUser_id(isToken.get(0).getId());
                        collectsMapper.insert(collectsObj);
                        //更新商品对应收藏数量
                        final QueryWrapper<Goods> wrapperGoodsCollectCount = new QueryWrapper<>();//查询该用户的所有收藏商品
                        wrapperGoodsCollectCount.eq("id", good);
                        final List<Goods> goods = goodsMapper.selectList(wrapperGoodsCollectCount);
                        final Integer collects_count = goods.get(0).getCollects_count();
                        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", good).set("collects_count", (collects_count + 1));//商品收藏数+1
                        goodsMapper.update(null, updateWrapper);

                        return new ResponseEntity<>(null, HttpStatus.CREATED);
                    } else {//此用户收藏过此商品---取消收藏
                        //找得到数据，删除一条数据---取消收藏
                        UpdateWrapper<Collects> deleteWrapper = new UpdateWrapper<>();//删除指定user_id、goods_id的收藏商品列
                        deleteWrapper.eq("user_id", isToken.get(0).getId())
                                .eq("goods_id", good);
                        collectsMapper.delete(deleteWrapper);

                        //更新商品对应收藏数量
                        final QueryWrapper<Goods> wrapperGoodsCollectCount = new QueryWrapper<>();//查询该用户的所有收藏商品
                        wrapperGoodsCollectCount.eq("id", good);
                        final List<Goods> goods = goodsMapper.selectList(wrapperGoodsCollectCount);
                        final Integer collects_count = goods.get(0).getCollects_count();
                        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", good).set("collects_count", (collects_count - 1));
                        goodsMapper.update(null, updateWrapper);

                        //查询收藏列表中该商品的所有收藏
                        final QueryWrapper<Collects> wrapperCollectCount = new QueryWrapper<>();//查询该用户的所有收藏商品
                        wrapperCollectCount.eq("goods_id", good);
                        final List<Collects> collectsListAll = collectsMapper.selectList(wrapperCollectCount);
                        if (collectsListAll.size() == 0) {//如果没有，则代表未被任何用户收藏，令is_collect=0
                            UpdateWrapper<Goods> updateWrapperIsCollect = new UpdateWrapper<>();
                            updateWrapperIsCollect.eq("id", good).set("is_collect", 0);
                            goodsMapper.update(null, updateWrapperIsCollect);
                        }
                        return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
                    }
                } else {
                    return new ResponseEntity<>(null, HttpStatus.NOT_ACCEPTABLE);
                }
            } else {
                final RegisterErrors registerErrors = new RegisterErrors();
                registerErrors.setMessage("Token Signature could not be verified.");
                registerErrors.setErrors("Token已失效");
                registerErrors.setStatus_code(401);
                return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
            }
        }
    }
}
